package com.songlin.bakejianshen;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.songlin.adapter.ViewPaperAdapter;
import com.songlin.model.Person;
import com.songlin.model.State;
import com.songlin.utils.BitmapUtils;
import com.songlin.utils.DBUtils;
import com.songlin.utils.InfoUtils;
import com.songlin.utils.StringOrDate;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    // 控件
    private ImageView mHeadImage;
    private EditText mEditCardNum;
    private EditText mEditName;
    private EditText mEditPhone;
    private ImageButton mBtnRegister;
    private Person mPerson;
    private Context context;
    private com.songlin.db.Person mLocalPerson;
    // 图片处理相关
    // 设置路径
    private String imageUri = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/photo.jpeg";

    private static final int TAKE_PICTURE = 0;
    private static final int FROM_ALBUM = 1;
    private static final int CROP_PICTURE = 2;

    private static final String[] m={"月卡","季卡","半年卡","年卡"};
    private int mCardNum = 1;
    private Spinner mSpinner;
    private ArrayAdapter<String> mAdapterSpinner;

    private int mWidth;
    private int mHeight;

    int mYear, mMonth, mDay;
    private boolean isImage = false;

    private ProgressDialog pd;

    public RegisterActivity() {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //隐藏应用程序标题栏    (能看到手机通知栏)
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_register);

        mHeadImage = (ImageView) findViewById(R.id.headView);
        mEditCardNum = (EditText) findViewById(R.id.edit_cardNum);
        ;
        mEditName = (EditText) findViewById(R.id.edit_name);
        ;
        mEditPhone = (EditText) findViewById(R.id.edit_phoneNum);
        ;
        mBtnRegister = (ImageButton) findViewById(R.id.btn_register);

        mSpinner = (Spinner)findViewById(R.id.cardType);
        mAdapterSpinner = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m);
        //设置下拉列表的风格
        mAdapterSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //将adapter 添加到spinner中
        mSpinner.setAdapter(mAdapterSpinner);

        //添加事件Spinner事件监听
        mSpinner.setOnItemSelectedListener(new SpinnerSelectedListener());

        //设置默认值
        mSpinner.setVisibility(View.VISIBLE);

        mHeadImage.setOnClickListener(this);
        mBtnRegister.setOnClickListener(this);

        mPerson = new Person();
        mLocalPerson = new com.songlin.db.Person();
        this.context = this;

        Point point = new Point();
        getWindowManager().getDefaultDisplay().getSize(point);
        mWidth = point.x;
        mHeight = point.y;

        final Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);

    }

    //使用数组形式操作
    class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                   long arg3) {
//            view.setText("你的血型是："+m[arg2]);
            toast("m[arg2]--->" + arg2);
            mCardNum = arg2 + 1;
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.headView: {
                showPickDialog();
            }
            break;
            case R.id.btn_register: {
                //注册按钮
                String card = mEditCardNum.getText().toString().trim();
                String name = mEditName.getText().toString().trim();
                String phone = mEditPhone.getText().toString().trim();

                // 监测是否为空
                if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(name)
                        || TextUtils.isEmpty(card)) {
                    toast("输入不完整");
                    return;
                }

                if(!isImage){
                    toast("一定要设置头像哦。。。。");
                    return;
                }

                int stateNow = DBUtils.getInstance().getState() + 1;

                mPerson.setCardNum(Integer.valueOf(card));
                mPerson.setName(name);
                mPerson.setPhone(phone);
                mPerson.setCardType(mCardNum);
                mPerson.setDate(new BmobDate(new Date(System.currentTimeMillis())));
                mPerson.setState(stateNow);

                mLocalPerson.setHeadName(card);
                mLocalPerson.setCardType(mCardNum);
                mLocalPerson.setName(name);
                java.util.Date utilDate=new Date();
                java.sql.Date sqlDate=new java.sql.Date(utilDate.getTime());
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                mLocalPerson.setDate(format.format(utilDate));
                mLocalPerson.setPhone(phone);
                mLocalPerson.setState(stateNow);

                //保存图片
                BitmapUtils.saveImageToGallery(RegisterActivity.this, BitmapFactory.decodeFile(imageUri.toString()), card);

                pd = new ProgressDialog(context);
                pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                pd.setTitle("提示");
                pd.setMessage("注册中。。。");
                pd.setIndeterminate(false);
                pd.setCancelable(true);
                pd.show();

                //检查是否注册
                checkIsRegister();
            }
            break;
        }
    }

    //检查是否注册
    private void checkIsRegister() {

        BmobQuery<Person> usersQuery = new BmobQuery<Person>();
        usersQuery.addWhereEqualTo("cardNum", mPerson.getCardNum());
        usersQuery.findObjects(new FindListener<Person>() {
            @Override
            public void done(List<Person> object, BmobException e) {
                if(e==null){
                    if (object.size() == 0){
                        // 插入图片
                        insertImage();
                    }else{
                        registerHandle.sendEmptyMessage(1);
                    }

                }else{
                    toast("查询失败："+ e.getMessage());
                }
            }
        });
    }

    private void insertImage() {
        final BmobFile bmobFile = new BmobFile(new File(imageUri));
        bmobFile.uploadblock(new UploadFileListener() {

            @Override
            public void done(BmobException e) {
                if(e==null){
                    //bmobFile.getFileUrl()--返回的上传文件的完整地址
                    toast("上传文件成功:" + bmobFile.getFileUrl());
                    mPerson.setHeadUrl(bmobFile.getFileUrl());

                    insertData();

                }else{
                    toast("上传文件失败：" + e.getMessage());
                }

            }

            @Override
            public void onProgress(Integer value) {
                // 返回的上传进度（百分比）
            }
        });
    }

    //插入数据
    private void insertData() {
        mPerson.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if(e==null){
                    toast("添加数据成功，返回objectId为："+objectId);


                    //g更新云端状态码
                    final State state = new State();
                    state.setState(mPerson.getState());
                    state.update(InfoUtils.STATE_OBJ, new UpdateListener() {

                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                toast("状态码更新成功:"+state.getUpdatedAt());
                                DBUtils.getInstance().upDateState(mPerson.getState());

                                DBUtils.getInstance().saveOnePerson(mLocalPerson);
                                registerHandle.sendEmptyMessage(0);
                            }else{
                                toast("更新失败：" + e.getMessage());
                            }
                        }

                    });

                }else{
                    toast("创建数据失败：" + e.getMessage());
                }
            }
        });
    }

    // Handle用于接收服务器返回消息
    Handler registerHandle = new Handler() {

        public void handleMessage(android.os.Message msg) {

            if (pd != null && pd.isShowing()) {
                pd.dismiss();
            }
            switch (msg.what) {
                case 0:
                    // 跳转
                    new AlertDialog.Builder(context)
                            .setIcon(R.mipmap.ic_launcher)
                            .setTitle("提示")
                            .setMessage("注册成功！")
                            .setPositiveButton("好呀",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialoginterface,
                                                int i) {
                                            finish();
                                        }
                                    }).show();
                    break;
                case 1:
                    // 跳转
                    new AlertDialog.Builder(context)
                            .setIcon(R.mipmap.ic_launcher)
                            .setTitle("提示")
                            .setMessage("该卡号已被注册")
                            .setPositiveButton("那好吧",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialoginterface,
                                                int i) {
                                            // 将输入框置为空
//                                            setEmpty();
                                        }
                                    }).show();
                    break;
                default:
                    break;
            }
        };

    };

    private void showPickDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示...")
                .setNegativeButton("相册", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        // 利用Intent打开相册
                        Intent album = new Intent(Intent.ACTION_GET_CONTENT);
                        // 将数据指明一个url
                        album.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                        // 指明 MIME 类型为 image
                        album.setType("image/*");
                        startActivityForResult(album, FROM_ALBUM);

                    }
                })
                .setPositiveButton("拍照", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();

                        // 没有判断SD卡是否存在，不知道会不会出问题
                        // 利用Intent启动相机
                        Intent camera = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        // 将拍照的图片保存到设置的路径之中
                        camera.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
                        // Intent的回调，传入TAKE_PICTURE
                        startActivityForResult(camera, TAKE_PICTURE);

                    }
                }).show();
    }

    // Intent消息的回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        float detal = mWidth / 600;

        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case TAKE_PICTURE:

                    cropImage(getImageUri(), 512, 512, CROP_PICTURE);
                    break;
                case FROM_ALBUM:
                    Uri uri = data.getData();
                    cropImage(uri, 512, 512, CROP_PICTURE);
                    break;
                case CROP_PICTURE:
                    // 获取剪切后的图片
                    Bitmap photo = null;
                    Bundle extra = data.getExtras();
                    if (extra != null) {
                        photo = (Bitmap) extra.get("data");
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        try {
                            photo.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(imageUri)));
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        mHeadImage.setImageBitmap(photo);
                        isImage = true;
                    }
                default:
                    break;
            }
        }

    }

    private void cropImage(Uri uri, int outputX, int outputY, int requestCode) {

        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        // 制定待裁剪的 image 所在路径 uri
        intent.setDataAndType(uri, "image/*");
        // 意图的 为 crop(裁剪) true
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后，输出图片的尺寸
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        // 取消人脸识别功能
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", true);

        startActivityForResult(intent, requestCode);
    }

    private Uri getImageUri() {
        return Uri.fromFile(new File(imageUri));
    }

    //测试输出
    private void toast(String str) {
        Toast.makeText(RegisterActivity.this, str, Toast.LENGTH_SHORT).show();
    }


}
